#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: ZhengShiQi
@file: conftest.py
@time: 2025/8/27 17:06
@desc: pytest配置文件
"""

import os
import sys
import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from tools.config_manager import TestConfig

# 添加项目根目录到sys.path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))


class DriverFactory:
    """驱动工厂类，用于创建浏览器驱动实例"""

    @staticmethod
    def _build_options(browser_config):
        """构建浏览器选项"""
        options = Options()
        
        # 添加浏览器参数
        if 'arguments' in browser_config:
            for arg in browser_config['arguments']:
                options.add_argument(arg)
        
        # 添加实验性选项
        if 'experimental_options' in browser_config:
            for key, value in browser_config['experimental_options'].items():
                options.add_experimental_option(key, value)
        
        return options

    @staticmethod
    def create_driver(browser_name="chrome", env_name="local"):
        """创建浏览器驱动实例"""
        config = TestConfig(env_name)
        browser_config = config.get_browser_config(browser_name)
        
        # 本地驱动
        options = DriverFactory._build_options(browser_config)
        driver = webdriver.Chrome(options=options)
        
        # 设置隐式等待
        driver.implicitly_wait(config.common.timeout)
        
        # 设置窗口大小
        if config.common.window_size:
            width, height = config.common.window_size
            driver.set_window_size(width, height)
        else:
            driver.maximize_window()
        
        return driver


@pytest.fixture(scope="session")
def config(request):
    """中央化配置管理"""
    env_name = request.config.getoption("--env", "local")
    return TestConfig(env_name)


@pytest.fixture(scope="session")
def driver_factory():
    """驱动工厂实例"""
    return DriverFactory()


@pytest.fixture(scope="function")
def browser(driver_factory, config):
    """带错误恢复的智能浏览器实例"""
    max_retries = 3
    retry_count = 2
    driver = None
    
    while retry_count < max_retries:
        try:
            driver = driver_factory.create_driver("chrome", config.env_name)
            break
        except Exception as e:
            retry_count += 1
            if retry_count >= max_retries:
                raise e
            print(f"浏览器初始化失败，正在重试 ({retry_count}/{max_retries}): {e}")
    
    yield driver
    
    # 确保浏览器被正确关闭
    if driver:
        try:
            driver.quit()
        except Exception as e:
            print(f"关闭浏览器时出错: {e}")
            # 强制终止可能的残留进程
            try:
                driver.service.stop()
            except:
                pass
        finally:
            # 清理driver引用
            driver = None